package com.woniuxy.happylife.gate.fliter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.woniuxy.happylife.entity.ResponseEntity;
import com.woniuxy.happylife.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.Duration;

/**
 * @Title: LoginFilter
 * @ProjectName: fourproject
 * @Description: TODO
 * @Author: chowinggum
 * @Date: 2022/2/10 17:01
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    //GlobalFilter拦截的核心方法
    //Mono:Gateway底层是Netty,NIO,不是以前的ServletAPI
    @Resource
    RedisTemplate<String,Object> redisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        if(true){
//            return chain.filter(exchange);
//        }
        System.out.println("进入loginfilter方法");
        ServerHttpRequest request = exchange.getRequest();
        //某些路径可以直接放行
        if (request.getURI().getPath().contains("login")) {
            System.out.println("请求登录页面，直接放行");
            return chain.filter(exchange);
        }
        //token验证
//        System.out.println("token验证");
        String token = request.getHeaders().getFirst("Authorization");
//        System.out.println(token);
        if(!StringUtils.isEmpty(token) && JwtUtil.verify(token)){
            System.out.println("token有效，放行");
            return chain.filter(exchange);
        }else{
            if(redisTemplate.opsForHash().get("token",token)!=null||redisTemplate.opsForHash().get("tokencopy",token)!=null){
                //将token覆盖一遍延长时间
                redisTemplate.opsForHash().put("token",token, Duration.ofMinutes(30));
                redisTemplate.opsForHash().put("tokencopy",token,Duration.ofMinutes(60));
                System.out.println("token有效，放行");
                return chain.filter(exchange);
            }else {
                System.out.println("token无效，拦截用户请求");
                return exchange.getResponse().writeWith(Mono.just(getDataBuffer(exchange)));
            }
        }


    }

    DataBuffer getDataBuffer(ServerWebExchange exchange){
        //自定义响应自定义JSON数据
        ServerHttpResponse response = exchange.getResponse();
        ResponseEntity<String> result = new ResponseEntity<>(401, "authentication", "先登录");
        //定义字节数组
        byte[] data=null;
        //序列化JSON
        try {
            data=new ObjectMapper().writeValueAsString(result).getBytes(StandardCharsets.UTF_8);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //封装成Data缓冲
        DataBuffer dataBuffer=response.bufferFactory().wrap(data);
        //设置JSON响应头，否则中文乱码
        response.getHeaders().add("Content-Type","application/json;charset=utf-8");
        return dataBuffer;
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
